<!--
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-06-02 17:59:44
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-06-03 22:11:30
 * @FilePath: \vue3_upload_file\vue3_upload_demo\src\pages\Upload\muti.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="muti-page-container">
    <el-form :model="form" label-suffix="：" label-position="left">
      <el-form-item label="文件名称">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="文件上传">
        <!-- 覆盖默认行为 -->
        <el-upload class="upload-demo" v-model:file-list="files" list-type="picture-card" :limit="10" multiple
          :http-request="handleCustomUpload" :on-remove="handleRemoveFile" :on-exceed="handleUploadExceed">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleUploadSubmit">选择确认上传</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';

import { uploadMutiFile } from '@/api/upload';
import { toast } from '@/utils/common';

// 路由
const router = useRouter();

// 表单数据
const form = reactive({
  name: '',
  files: []
});

// 上传文件列表
const files = ref([]);

// 重置表单数据
const handleResetData = data => {
  for (const key in data) {
    form[key] = data?.[key];
  }
}

// 覆盖默认行为
const handleCustomUpload = data => {
  const { file } = data;

  form.files = form.files.concat(file);
}

// 个数限制
const handleUploadExceed = () => {
  toast('超出上传数量限制', 'warning')
}

// 移除图片
const handleRemoveFile = file => {
  form.files = form.files.filter(item => item.uid !== file.uid);
}

// 确认上传
const handleUploadSubmit = async () => {
  // 封装表单数据
  const formData = new FormData();
  formData.append('name', form.name);
  // 遍历文件列表
  for (let i = 0; i < form.files.length; i++) {
    formData.append('file', form.files[i]);
  }
  // 接口上传
  const { success, msg } = await uploadMutiFile(formData).finally(() => handleResetData({ name: '', files: [] }));

  // 是否上传成功
  if (success) {
    files.value = [];
    toast(msg, 'success');
    router.push('/source');
  }
}

</script>

<style lang="less" scoped>
.muti-page-container {
  width: 100%;
  height: 100%;
  @apply p-10;
}
</style>